# -*- coding: utf-8 -*-
# created on 2016/8/18
from mathsolver.functions.shulie.Fundamental import sl_xiangs
from mathsolver.functions.base import *
from mathsolver.functions.shuyushi import HuaJian
from sympy import Tuple
from mathsolver.functions.mathematica.mathematicaSolve import MathematicaSimplify


class ShuYuShiCompute(BaseFunction):
    def solver(self, *args):
        # assert not re.search("sin|cos|tan|csc|sec|cot", str(args[0].value)), "sinpoly unacceptable"
        poly = args[0].sympify()
        symbols = poly.free_symbols
        symbols = list(symbols)
        poly_xiangs = sl_xiangs(poly)
        if poly_xiangs:
            for item in poly_xiangs:
                symbols.append(sympify(item))
        symbols = set(symbols)
        if len(symbols) == 0:
            if len(str(poly)) < 10:
                value = simplify(poly)
            elif "I" in str(poly):
                from sympy import expand
                value = simplify(poly)
                value = expand(value)
            else:
                value = MathematicaSimplify().solver(*args).output[0].sympify()

            self.steps.append(["化简得:%s" % new_latex(value), ""])
            self.output.append(BaseNumber(value))

        else:
            try:
                stepsolver = HuaJian().solver(*args)
                stepsolver.output[0].intermediate = False
                poly = stepsolver.output[0].value
                symbols = poly.free_symbols
                symbols = list(symbols)
                poly_xiangs = sl_xiangs(poly)
                if poly_xiangs:
                    for item in poly_xiangs:
                        symbols.append(sympify(item))
                symbols = set(symbols)
                # self.append(stepsolver)
            except Exception:
                pass

            unknown_symbols = set(symbols).difference([Symbol("x"), Symbol("y")])
            self.steps.append(["%s " % new_latex(poly), ""])

            ans = self.search_multiple(unknown_symbols)
            new_values = []
            if ans is None:
                select_key = [key for key in self.known if not isinstance(key, str) and key in unknown_symbols]
                if select_key:
                    k = select_key[0]
                    values = self.search(k)
                    if isinstance(values, FiniteSet):
                        for v in values:
                            new_values.append(poly.subs({k: v}).simplify())
                        # self.steps.append(["=%s" % latex(), ""])
            else:

                if isinstance(ans, PieceWise):
                    values = [ans_value for ans_value, ans_cond in ans.pieces]
                    var = ans.var
                else:
                    values = list(ans)
                    var = unknown_symbols

                for ans_value in values:
                    if not isinstance(ans_value, (Tuple, tuple)):
                        ans_value = [ans_value]

                    symbol_value = dict(
                        [(sym, v.subs({Symbol("C_1"): 0, Symbol("C_2"): 0})) for sym, v in zip(var, ans_value) if
                         not isinstance(v, Set)])
                    if symbol_value:
                        new_values.append(poly.subs(symbol_value).simplify())

            new_values_2 = set()
            for i, v in enumerate(set(new_values)):
                if len(v.free_symbols) == 1:
                    sym = list(v.free_symbols)[0]
                    values = [v.subs({sym: num}).simplify() for num in range(1, 5)]
                    values = [value for value in values if str(value) != "zoo" and str(value) != "nan"]
                    if len(set(values)) == 1:
                        v = values[0]
                elif len(str(v)) > 10:
                    v = MathematicaSimplify().solver(BasePoly(v)).output[0].sympify()

                new_values_2.add(v)

            for i, v in enumerate(new_values_2):
                if i:
                    self.steps.append(["或", ""])

                self.steps.append(["= %s" % new_latex(v), ""])

            if len(new_values_2) == 1:
                self.output.append(BaseNumber(list(new_values_2)[0]))
            else:
                self.output.append(BaseNumbers(new_values_2))

        if "conjugate" in str(args[0].value):
            self.label.add("共轭复数")
        # self.output.append(BaseNumber(poly.subs(symbol_value).simplify()))
        return self
